using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;

namespace SymAutomate
{
    /// <summary>
    /// Handles Global  functions
    /// Error Numbers 080-099; Reference file ErrorNumbers.txt for more information.
    /// 080 Error: While attempting to write to config file, config file could not be found. Working directory may not be set correctly.
    /// 081 Error: While attempting to write to config file, config file was modified less than 2 minutes ago. Possibly another thread was writing to the file.
    class GlobalFunctions
    {
        /// <summary>
        /// Returns the int value for the specified string; null otherwise.
        /// </summary>
        /// <param name="_Input"></param>
        /// <returns></returns>
        public static int? GetInt(string _Input)
        {
            if (string.IsNullOrEmpty(_Input))
                return null;

            int? _ReturnValue = null;
            int _Result = 0;
            if (int.TryParse(_Input, out _Result))
            {
                _ReturnValue = _Result;
            }
            return _ReturnValue;
        }

        /// <summary>
        /// Returns true/false based on the input value.
        /// Throws ArgumentException if input value cannot be interpreted.
        /// </summary>
        /// <param name="_Input"></param>
        /// <returns></returns>
        public static bool GetBooleanValue(string _Input)
        {
            if (string.IsNullOrEmpty(_Input))
                throw new ArgumentException("Valid values are 0, 1, false, true");
            if (_Input.Trim().ToLower() == "true" || _Input.Trim().ToLower() == "1")
                return true;
            if (_Input.Trim().ToLower() == "false" || _Input.Trim().ToLower() == "0")
                return false;
            throw new ArgumentException("Valid values are true or false");
        }

        /// <summary>
        /// Returns the int value for thie input value.
        /// Throws ArgumentException if input value cannot be interpreted.
        /// </summary>
        /// <param name="_Input"></param>
        /// <returns></returns>
        public static int GetIntValue(string _Input)
        {
            if (string.IsNullOrEmpty(_Input))
                throw new ArgumentException("String cannot be parsed to number");
            int _Result;
            if (int.TryParse(_Input, out _Result))
            {
                return _Result;
            }
            else
            {
                throw new ArgumentException("String '" + _Input + "' cannot be parsed to number");
            }
        }

        /// <summary>
        /// Updates the config file value for the specified key
        /// </summary>
        /// <param name="_Key"></param>
        /// <param name="_Value"></param>
        /// <param name="_CheckFileLastWriteTimeInSeconds"></param>
        public static void WriteToConfigFile(string _Key, string _Value, int _CheckFileLastWriteTimeInSeconds)
        {
            if (string.IsNullOrEmpty(_Key))
                throw new ArgumentException("Key must not be null or empty");
            if (string.IsNullOrEmpty(_Value))
                throw new ArgumentException("Value must not be null or empty");

            if (File.Exists("SymAutomate.exe.config"))
            {
                if (_CheckFileLastWriteTimeInSeconds != 0 &&
                    File.GetLastWriteTime("SymAutomate.exe.config") >= DateTime.Now.AddSeconds(-1 * _CheckFileLastWriteTimeInSeconds))
                {
                    throw new ReturnException("081 Error: While attempting to write to config file, config file was modified less than 2 minutes ago. Possibly another thread was writing to the file.");
                }

                string _ConfigFileContents = File.ReadAllText("SymAutomate.exe.config");
                Regex _Regex = new Regex("(key=\"" + _Key + "\" value=\"(.*?)\")");
                MatchCollection _MatchCollection = _Regex.Matches(_ConfigFileContents);

                if (_MatchCollection.Count == 0)
                    throw new ArgumentException("Specified key is not found in config file");
                if (_MatchCollection.Count > 1)
                    throw new ArgumentException("Specified key is found more than once in config file");

                _ConfigFileContents = _ConfigFileContents.Replace(_MatchCollection[0].Groups[1].Value, _MatchCollection[0].Groups[1].Value.Replace("value=\"" + _MatchCollection[0].Groups[2].Value + "\"", "value=\"" + _Value + "\""));
                File.WriteAllText("SymAutomate.exe.config", _ConfigFileContents);
            }
            else
            {
                throw new ReturnException("080 Error: While attempting to write to config file, config file could not be found. Working directory may not be set correctly.");
            }
        }
    }
}
